package com.yc.exam.biz;

import com.yc.exam.bean.Exam;
import com.yc.exam.bean.ExamDetail;
import com.yc.exam.bean.Question;
import com.yc.exam.mapper.ExamDetailMapper;
import com.yc.exam.mapper.ExamMapper;
import com.yc.exam.mapper.QuestionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/8/17
 * Email haijunzhou@hnit.edu.cn
 */
@Service
public class ExamBiz {

    @Autowired
    QuestionMapper questionMapper;
    @Autowired
    ExamMapper examMapper;
    @Autowired
    ExamDetailMapper examDetailMapper;

    @Transactional
    public void commit(Exam exam){
        // 查询题目信息
        // 统计分数: 现在的分数是固定分数, 填空2, 单选3分, 多选5, 判断1
        int sum = 0;
        for (ExamDetail detail : exam.getDetails()) {
            Question question = questionMapper.selectById(detail.getQid());
            String[] answers = detail.getAnswer().split(";");
            String[] items = question.getItems().split(";");
            detail.setTf(0);
            if ("填空题".equals(question.getType())){
                for (int i = 0; i < items.length; i++) {
                    detail.setTf(detail.getTf()+(items[i].equals(answers[i])?1:0));
                }
                if(detail.getTf()>0){
                    sum += detail.getTf() * 2;
                }
            } else if (question.getType().endsWith("选题")){
                boolean isTrue = true;
                for (int i = 0; i < items.length; i++) {
                    if (items[i].startsWith("$")) {
                        items[i] = items[i].substring(1);
                    } else {
                        items[i] = " ";
                    }
                    if(items[i].equals(answers[i]) == false){
                        isTrue = false;
                        break;
                    }
                }
                if(isTrue){
                    sum += "单选题".equals(question.getType()) ? 3 : 5;
                    // 解决选择题bug
                    detail.setTf(1);
                }
            } else {
                detail.setTf(question.getItems().equals(detail.getAnswer())?1:0);
                if(detail.getTf()==1){
                    sum += 1;
                }
            }
            exam.setScore(sum);
        }

        examMapper.insert(exam);
        for (ExamDetail examDetail : exam.getDetails()) {
            examDetail.setEid(exam.getId());
            examDetailMapper.insert(examDetail);
        }

    }

}
